package com.wobito.controller.admin;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wobito.common.constants.BaseResponse;
import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import com.wobito.common.utils.AliOSSUtils;
import com.wobito.common.utils.FileTypeUtils;
import com.wobito.common.utils.MimeTypeUtils;
import com.wobito.common.utils.ResultUtils;
import com.wobito.pojo.bean.ConfigData;
import com.wobito.pojo.bean.ConfigType;
import com.wobito.pojo.dto.config.ConfigPictureDTO;
import com.wobito.pojo.validator.ValidatorUtils;
import com.wobito.pojo.vo.config.ConfigPictureVO;
import com.wobito.service.IConfigDataService;
import com.wobito.service.IConfigTypeService;
import com.wobito.system.aspect.OperLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: lambyang
 * @CreateTime: 2024-09-23
 * @Description: 参数配置管理
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/manage/configValue")
@Api(tags = "参数配置中心")
public class ConfigUrationController {

    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private IConfigTypeService configTypeService;
    @Autowired
    private IConfigDataService configDataService;

    @GetMapping("/getConfigList")
    @ApiOperation(value = "获取可配置参数信息列表")
    @OperLog(thing = "获取可配置参数信息列表")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getConfigValueList() {
        Map<String, Object> configValueMap = new HashMap<>();
        ConfigType configOpenTime = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, "system:device:openTime"));
        ConfigType configColseTime = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, "system:device:closeTime"));
        ConfigType configBorrowMaxTime = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, "borrow:book:time"));
        ConfigType configRenewMaxTime = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, "renew:book:time"));
        ConfigType configExpiredMaxTime = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, "expired:reminder:time"));
        List<ConfigData> configPictures = configDataService.list(new LambdaQueryWrapper<ConfigData>().eq(ConfigData::getConfigKey, "picture:list:config"));
        List<ConfigPictureDTO> configPictureDTOS = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(configPictures)) {
            configPictureDTOS = configPictures.stream().map(p -> {
                ConfigPictureDTO pictureDTO = new ConfigPictureDTO();
                pictureDTO.setIndex(p.getConfigLabel());
                pictureDTO.setUrl(p.getConfigValue());
                return pictureDTO;
            }).collect(Collectors.toList());
        }
        configValueMap.put("[设备自动开机时间]-system:device:openTime", configOpenTime.getConfigValue());
        configValueMap.put("[设备自动关机时间]-system:device:closeTime", configColseTime.getConfigValue());
        configValueMap.put("[借书最大时间]-borrow:book:time", configBorrowMaxTime.getConfigValue());
        configValueMap.put("[续借最大时间]-renew:book:time", configRenewMaxTime.getConfigValue());
        configValueMap.put("[过期提醒时间]-expired:reminder:time", configExpiredMaxTime.getConfigValue());
        configValueMap.put("[图片配置数据]-picture:list:config", configPictureDTOS);
        return ResultUtils.success(configValueMap);
    }

    @PutMapping("/addPicture/{configKey}")
    @ApiOperation(value = "添加图片配置")
    @OperLog(thing = "添加图片配置")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse addPicture(@PathVariable("configKey") String configKey, @Valid ConfigPictureVO configPictureVO) {
        String fileUrl="";
        if (!ValidatorUtils.isFileName(configPictureVO.getFile().getOriginalFilename())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件名称不合法(只允许存在数字 字母 - _)!");
        }
        if (ArrayUtil.contains(MimeTypeUtils.IMAGE_EXTENSION,FileTypeUtils.getFileType(configPictureVO.getFile().getOriginalFilename()))) {
            try {
                fileUrl= aliOSSUtils.upload(configPictureVO.getFile());
                configDataService.addPicture(configKey,new ConfigPictureDTO(configPictureVO.getIndex(),fileUrl));
            } catch (IOException e) {
                log.error(e+":"+e.getMessage());
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败!");
            }
        }
        return ResultUtils.success("图片上传成功");
    }

    @PostMapping("/updateConfigValue/{configKey}")
    @ApiOperation(value = "修改参数配置")
    @OperLog(thing = "修改参数配置")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse updateConfigValue(@PathVariable("configKey") String configKey, @RequestParam(value = "value") String value) {
        if (configKey.equals("system:device:openTime") || configKey.equals("system:device:closeTime")) {
            if (!ValidatorUtils.isTime(value)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "时间格式错误,请输入00:00-23:59的有效时间!");
            }
        }
        if (configKey.equals("borrow:book:time")) {
            if (!ValidatorUtils.isNumber(value)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入有效数字!");
            }
        }
        ConfigType configType = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, configKey));
        if (ObjectUtil.isNull(configType)) {
            throw new BusinessException(ErrorCode.NULLPARAMS_ERROR, "该配置不存在!");
        }
        configType.setConfigValue(value);
        return ResultUtils.success(configTypeService.updateById(configType));
    }

    @DeleteMapping("/delPicture/{configKey}")
    @ApiOperation(value = "删除图片配置")
    @OperLog(thing = "删除图片配置")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse delPicture(@PathVariable("configKey") String configKey, @RequestParam(value = "index") String index) {
        ConfigData configData = configDataService.getOne(new LambdaQueryWrapper<ConfigData>().eq(ConfigData::getConfigKey, configKey).eq(ConfigData::getConfigLabel, index));
        if (ObjectUtil.isNull(configData)) {
            throw new BusinessException(ErrorCode.NULLPARAMS_ERROR, "该图片不存在!");
        }
        aliOSSUtils.delete(configData.getConfigValue());
        return ResultUtils.success(configDataService.removeById(configData.getId()));
    }
}
